package com.peng.leetcode.list;

/**
 * SortList
 * 剑指 Offer II 077. 链表排序
 * https://leetcode.cn/problems/7WHec2/
 * 链表排序：使用归并排序算法排序链表
 * 需要注意排序的比较，写错了就成降序了
 * 快慢指针寻找链表的中心节点，
 * <p>
 * Created on 2022/11/18
 *
 * @author lupeng
 */
public class SortList {

    public static void main(String[] args) {
        //4,2,1,3
        ListNode head = new ListNode(4, new ListNode(2, new ListNode(1, new ListNode(3, null))));
        ListNode listNode = new SortList().sortList(head);
        System.out.println(listNode);
    }

    public ListNode sortList(ListNode head) {
        return sort(head);
    }

    public ListNode sort(ListNode head) {
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return head;
        }
        ListNode middle = findMiddle(head);
        ListNode l1 = head;
        ListNode l2 = middle.next;
        middle.next = null;
        l1 = sort(l1);
        l2 = sort(l2);
        return merge(l1, l2);
    }

    public ListNode merge(ListNode l1, ListNode l2) {
        ListNode sentry = new ListNode();
        ListNode curr = sentry;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                curr.next = l1;
                l1 = l1.next;
            } else {
                curr.next = l2;
                l2 = l2.next;
            }
            curr = curr.next;
        }
        if (l1 != null) {
            curr.next = l1;
        } else if (l2 != null) {
            curr.next = l2;
        }
        return sentry.next;
    }

    public ListNode findMiddle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
}
